package com.jbp.aspect;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.jbp.service.ApiLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 系统日志，切面处理类，记录日志
 */
@Aspect
@Component
@Configuration
public class SysLogAspect {

	private Logger log= LoggerFactory.getLogger(SysLogAspect.class);

	@Autowired
	private ApiLogService apiLogService;

	@Around("execution(*  com.jbp.controller.*.*(..))")
	public Object process(ProceedingJoinPoint joinPoint) throws Throwable {
		//类和方法名称
		String classAndMethodName =joinPoint.getTarget().getClass().getSimpleName() + "." + joinPoint.getSignature().getName();
		try {
//			String params = "";
//			if (!classAndMethodName.toLowerCase().contains("login") && !classAndMethodName.toLowerCase().contains("password")) {
//				params = JSONArray.toJSONString(filterParamList(joinPoint));
//			}
//			log.info("执行：{},入参：{}", classAndMethodName, params);
//			apiLogService.save(classAndMethodName, params);
		} catch (Exception e) {
		}
		//响应结果
		Object res = joinPoint.proceed();
//		log.info("执行：{},出参：{}", classAndMethodName, JSON.toJSONString(res));
		return res;

	}

	/**
	 * 过滤参数列表
	 * @param joinPoint
	 * @return
	 */
	private List<Object> filterParamList(ProceedingJoinPoint joinPoint) {
		List<Object> paramsList = new ArrayList<>();
		Object[] arrays = joinPoint.getArgs();
		for (int i = 0; i < arrays.length; i++) {
			if (!(arrays[i] instanceof HttpServletRequest)) {
				paramsList.add(arrays[i]);
			}
		}
		return paramsList;
	}

	
}
